package com.lipei.vrp;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class FiletoDB {

	public static final String OUTPUT_SQL = "output.sql";

	public static void main(String[] args) {

		if (args.length < 2) {
			System.out.println("error in arguement.");
			System.out.println("usage: opt.filename vrp.filename");
			return;
		}

		Vrp vrp = null;
		Opt opt = null;
		try {
			opt = Opt.optReader(args[0]);
			vrp = Vrp.vrpReader(args[1]);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (vrp == null || opt == null) {
			throw new RuntimeException("can't read from file");
		}
		StringBuffer buf = new StringBuffer();

		buf.append("insert into vrp.solomonvrp(name,capacity) values('"
				+ vrp.name + "'," + vrp.capacity + ");");

		buf.append("\r\n");
		buf.append("\r\n");

		int i = 0;
		for (VrpData vrpdata : vrp.data) {
			i++;
			buf.append("insert into vrp.solomonvrpdata(solomonvrp,customerno,xcoord,ycoord,demand) values('"
					+ vrp.name
					+ "',"
					+ i
					+ ","
					+ vrpdata.xcoord
					+ ","
					+ vrpdata.ycoord + "," + vrpdata.demand + ");");
			buf.append("\r\n");
		}

		buf.append("\r\n");

		optsql(vrp, opt, buf);

		buf.append("\r\n");
		buf.append("\r\n");
		// buf.append("exit;\r\n");
		try {
			BufferedWriter output = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(OUTPUT_SQL)));
			output.write(buf.toString());
			output.close();

			Main.runSql(OUTPUT_SQL);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		System.out.println("oyeah!");
	}

	public static void optsql(Vrp vrp, Opt opt, StringBuffer buf) {
		int i;
		DecimalFormat format = new DecimalFormat("0.0000");
		buf.append("insert into vrp.result(solomonvrp,solution,resulttype,routenumber,pointnumber,capacity,AlgorithmType) values('"
				+ vrp.name
				+ "',"
				+ format.format(opt.cost)
				+ ",'"
				+ opt.resulttype.getName()
				+ "',"
				+ opt.routes.size()
				+ ","
				+ vrp.dimension
				+ ","
				+ vrp.capacity
				+ ",'"
				+ opt.algtype.getName() + "');");
		buf.append("\r\n");
		buf.append("set @id=LAST_INSERT_ID();\r\n");

		buf.append("\r\n");

		i = 0;
		for (ArrayList<Integer> list : opt.routes) {
			i++;
			buf.append("insert into vrp.resultroute(resultref,indexxxx) values(@id,"
					+ i + ");");
			buf.append("\r\n");
			buf.append("\r\n");

			buf.append("set @routeid=LAST_INSERT_ID();\r\n");
			buf.append("\r\n");

			int j = 0;
			for (Integer value : list) {
				j++;
				buf.append("insert into vrp.routes(resultroutref,indexxxx,value) values(@routeid,"
						+ j + "," + value + ");");
				buf.append("\r\n");
			}
		}
	}
}
